/*!
 * nodeweb - app.js
 */

/*
 *  模块依赖
 */
// var redisStore = require('connect-redis')(session); // redis
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var session = require('express-session');
var flash = require('connect-flash');
var log4js = require('log4js');
var app = express();

var manage = require('./src/manage'); // 后台
var api    = require('./src/api');    // API
var web    = require('./src/web');    // 前台

// log4js
log4js.configure(__dirname+'/config/bin/log4j.json',{});
var logger = log4js.getLogger('app');
logger.setLevel('INFO');

// 环境配置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// app.set('view engine', 'html');
// app.engine('html', require('ejs-mate'));
app.locals._layoutFile = 'layout.html';
app.enable('trust proxy');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(log4js.connectLogger(logger, {level: 'auto', format:':method :url'}));

// session
app.use(session({
  resave:false,
  saveUninitialized: true,
  secret:'nodeweb',
  cookie: {maxAge:60 * 60 * 24 * 30}
}));

// 静态文件目录
app.use(express.static(path.join(__dirname, '/public')));
app.use(flash());

// html 模板
app.engine('.html', ejs.__express);
// app.set("view options",{"open":"{{","close":"}}"});
app.set('view engine', 'html');

// 验证拦截器
app.use('/*.action', function(req, res, next){
  var url = req.originalUrl;
  if(url != '/login' && url.indexOf('html')==-1){
    checkLogin(req, res, next);
  }else{
    next();
  }
});
// 检查用户登录状态
checkLogin = function(req,res,next) {
  if(!req.session.user){
    var resMap={};
    resMap.status=4;
    resMap.message='用户登录过期或已失效,请重新登录';
    resMap.result=[];
    res.send(resMap);
    return false;
  }else{
    next();
  }
};

app.use('/*.html', function(req, res, next){
  var url = req.originalUrl;
  next();
});

// 路由
app.use('/', manage);
app.use('/api/*', api);
app.use('/activity/*', web);

// 404处理
app.use(function(req, res, next) {
  console.log("页面没发现:"+req.originalUrl);
  if(req.originalUrl.indexOf('.action') != -1 || req.originalUrl.indexOf('.json') != -1){
    var resMap={};
    resMap.status=404;
    resMap.message='请检查URL地址';
    resMap.result=[];
    res.send(resMap);
  }else{
    var err = new Error('Not Found 404');
    err.status = 404;
    res.render(path.join(__dirname, 'views/404'),{
      error:{
        status:404,
        message:"页面没发现",
        stack:"test"
      }
    });
  }
});

// 加载错误处理
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    logger.log(err.message);
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(err.status || 500);
  res.render(path.join(__dirname, 'views/error'), {
    message: err.message,
    error: {}
  });
});

// 日志
exports.logger=function(name){
  var logger = log4js.getLogger(name);
  logger.setLevel('INFO');
  return logger;
};

module.exports = app;
